<template>
  <div label="团队列表" name="详情">
    <div :style="{ width: '100px' }">
      <el-checkbox v-model="isadmin" label="是否官方创建" />
    </div>
    <div class="row">
      <div class="col">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="团队名">
            <el-input v-model.lazy="like" placeholder="请输入团队名称" />
          </el-form-item>
          <el-form-item label="团队等级">
            <el-select v-model="form.grade" clearable>
              <el-option label="免费客户（Level 0）" :value="0"></el-option>
              <el-option label="黄金客户（Level 1）" :value="1"></el-option>
              <el-option label="铂金客户（Level 2）" :value="2"></el-option>
              <el-option label="钻石客户（Level 3）" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="start">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <Addteam v-bind="{ ID: IID, team: Tteam, create, closed, packegekey }"></Addteam>

    </div>

    <el-table :data="tableData" height="65vh" border class="cu" style="width: 100%" @sort-change="sortchange"
      @cell-click="userhandleCurrentChange ? () => { } : handleClick" @selection-change="handleChange"
      :highlight-current-row="!!userhandleCurrentChange"
      @current-change="(e) => p.userhandleCurrentChange ? userCurrentChange(e) : $router.push({ name: '团队', params: { ID: e.ID } })">
      <el-table-column v-for="v in tableattr" :key="v.label" v-bind="{ ...v }"></el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="default" type="primary" @click.stop="IID = scope.row.ID">修改</el-button>
          <el-button size="default" type="danger" @click.stop="del(scope.row.ID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :hide-on-single-page="true" @current-change="handleCurrentChange" :page-size="Number(limit)"
      layout="prev, pager, next" :total="count"></el-pagination>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  watch,
  onMounted,
} from "vue";
import Addteam from "./addteam.vue";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import { toLocaleDateString } from "../../../util/time";
import { Team } from "../data";
import study from "../../../mysql_interface/studycodemodel";
import { TtableU } from "../../../interface";
import { asyncadmindelteam } from "../../../api";
import { Storekey } from "../../../interface";

const p = defineProps<{ tablekey?: Array<keyof study.Iteam>, handleSelectionChange?: (n: study.Iteam[]) => void, selectarr?: number[], userhandleCurrentChange?: (n: study.Iteam) => void }>()


const gradez = [
  '免费客户（Level 0）',
  '黄金客户（Level 1）',
  '铂金客户（Level 2）',
  '钻石客户（Level 3）',
]



const _tableattr: TtableU<study.Iteam>[] = [
  {
    label: "团队id",
    prop: "ID",
    sortable: true,
    width: 120,
  },
  {
    label: "团队名称",
    prop: "name",
    sortable: true,
  },
  {
    label: "创建者",
    prop: "userid",
    formatter: ({ user }) => user?.name || "",
    sortable: true,
    width: 120,
  },
  // {
  //   label: "类型",
  //   prop: "type",
  //   sortable: true,
  // },
  {
    label: "等级",
    prop: "grade",
    sortable: true,
    formatter: ({ grade }) => gradez[grade || 0],
    width: 160,
  },
  {
    label: "公告",
    prop: "info",
    width: 120,
  },
  {
    label: "是否官方创建",
    prop: "isadmin",
    formatter: ({ isadmin }) => !isadmin ? '是' : '否',
    width: 120,
  },
  {
    prop: "createdAt",
    label: "创建时间",
    formatter: ({ createdAt }) => formatter(createdAt),
    sortable: true,
    width: 120,
  },
];

const tableattr = computed(() => {
  const tablekey = p.tablekey;
  if (!tablekey) return _tableattr;
  return _tableattr.filter(({ prop }) => {
    if (prop) {
      return tablekey.includes(prop);
    }
  });
});

const sortable = ref("DESC");
const IID = ref<number | undefined | boolean>();
const limit = ref(20);
const offset = ref(0);
const order = ref("ID");
const like = ref("");
const form = reactive<study.Iteam>({
  isadmin: false
});

const isadmin = computed({
  get() {
    return !form.isadmin
  },
  set(v) {
    form.isadmin = !v
  }
})

const store = useStore(Storekey);
const packegekey = computed(() => {
  return store.state.packegekey?.rows;
});
const tableData = computed<study.Iteam[]>(() => {
  return store.getters.getteam;
});

const Tteam = computed<study.Iteam>(() => {
  if (IID.value) {
    return tableData.value.find((v) => v.ID == IID.value);
  }
  return {
    isadmin: false,
    color: '-cheng',
    isranking: true,
    grade: 0
  };
});

const count = computed<number>(() => {
  return store.getters.getteamcount;
});

function create() {
  IID.value = undefined;
}

onMounted(() => {
  store.dispatch("actionpackegekey");
  start();
});

async function start() {
  try {
    let z;
    if (like.value) {
      z = ["name", like.value];
    }
    store.dispatch("actionteam", {
      _limit: limit.value,
      _offset: offset.value,
      _order: order.value,
      _sortable: sortable.value,
      _like: z,
      ...form
    });
  } catch (e: any) {
    ElMessage.error(e);
  }
}

async function closed() {
  await start();
  IID.value = !IID.value;
}

function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
}

function sortchange(row: { prop: string; order: string }) {
  const { prop } = row;
  if (row.order == "descending") {
    sortable.value = "DESC";
  } else {
    sortable.value = "ASC";
  }
  order.value = prop;
}
function formatter(updatedAt?: string | number | Date) {
  return toLocaleDateString(updatedAt);
}

function handleChange(data: study.Iteam[]) {
  if (p.handleSelectionChange) p.handleSelectionChange(data);
}

function userCurrentChange(data: study.Iteam) {
  if (p.userhandleCurrentChange) p.userhandleCurrentChange(data);
}

async function del(ID: any) {
  ElMessageBox.confirm("确定要删除团队？", "提示").then(async () => {
    try {
      await asyncadmindelteam({ ID });
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      await start();
    } catch (e: any) {
      ElMessage({
        message: e,
        type: "error",
      });
    }
  });
}
watch(() => [limit.value, offset.value, order.value, sortable.value], () => {
  start()
})

watch(() => like.value, () => {
  limit.value = 20;
  offset.value = 0;
})
</script>